package api

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	db "slgw_web/application/gormdb"
	"slgw_web/serial/pac"

	"openzbox.com/frame/echo"
	models "openzbox.com/frame/echo/models/sl_gw01"
	"openzbox.com/frame/echo/response"
)

// 修改系统升级信息
func EditSysUpgrade(ctx echo.Context) error {
	var req models.EditSysUpgradeRequest
	if err := ctx.Bind(&req); err != nil {
		// 处理参数绑定错误
		//	ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return response.FailResult(1, err.Error(), ctx)

	}
	db := db.GetDB()
	if req.SysUpgrade.ID != 0 {
		//修改

		if err := db.Model(&models.SysUpgrade{}).Where("id = ?", req.SysUpgrade.ID).Updates(req.SysUpgrade).Error; err != nil {
			// 处理更新错误
			return response.FailResult(1, err.Error(), ctx)

		}
	} else {
		//新增
		//先判断是否存在，如果存在删除其他的 再新增
		sysUpgrade := []models.SysUpgrade{}
		db.Find(&sysUpgrade)
		if len(sysUpgrade) > 0 {
			db.Delete(&sysUpgrade)
		}
		if err := db.Create(&req.SysUpgrade).Error; err != nil {
			return response.FailResult(1, err.Error(), ctx)

		}
	}
	return response.SuccessResultWithEmptyData(ctx)
}

// 获取系统升级信息
func GetSysUpgrade(ctx echo.Context) error {
	//定义文章结构体切片
	sysUpgrade := models.SysUpgrade{}
	db := db.GetDB()
	//查询所有文章,以及文章的分类Preload
	db.First(&sysUpgrade)
	return response.SuccessResult(sysUpgrade, ctx)

}

// FTP升级
func FTPUpgrade(ctx echo.Context) error {
	sysUpgrade := models.SysUpgrade{}
	db := db.GetDB()
	db.First(&sysUpgrade)
	if sysUpgrade.ID == 0 {
		return response.FailResult(1, "升级失败,ftp升级数据未填写", ctx)
	}
	// exe := "ftpget -u " + sysUpgrade.FTPUN + " -p " + sysUpgrade.FTPPW + " -P " + sysUpgrade.FTPPORT + " " + sysUpgrade.FTPIP + " " + sysUpgrade.FTPFN
	// if sysUpgrade.FTPMOD == "0" { //匿名登录
	// 	exe = "ftpget -P " + sysUpgrade.FTPPORT + " " + sysUpgrade.FTPIP + " " + sysUpgrade.FTPFN
	// }
	exe := "wget ftp://" + sysUpgrade.FTPUN + ":" + sysUpgrade.FTPPW + "@" + sysUpgrade.FTPIP + ":" + sysUpgrade.FTPPORT + "/" + sysUpgrade.FTPFN
	if sysUpgrade.FTPMOD == "0" { //匿名登录
		exe = "wget ftp://" + sysUpgrade.FTPIP + ":" + sysUpgrade.FTPPORT + "/" + sysUpgrade.FTPFN
	}
	cmd := exec.Command("sh", "-c", exe)
	fmt.Println("FTP升级指令:", exe)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err := cmd.Run()
	if err != nil {
		return response.FailResult(1, "FTP升级指令失败,"+err.Error(), ctx)
	} else {
		//移动文件
		exe2 := "mv " + sysUpgrade.FTPFN + " /app/UpDateFile/GoApp"
		cmd2 := exec.Command("sh", "-c", exe2)
		fmt.Println("移动文件指令:", exe2)
		cmd2.Stdout = os.Stdout
		cmd2.Stderr = os.Stderr

		err2 := cmd2.Run()
		if err2 != nil {
			return response.FailResult(1, "移动文件指令失败,"+err2.Error(), ctx)
		}
	}
	return response.SuccessResultWithEmptyData(ctx)
}

func UploadUpgrade(ctx echo.Context) error {
	// 解析请求体
	reader, err := ctx.Request().MultipartReader()
	if err != nil {
		return response.FailResult(1, "无法解析请求体,"+err.Error(), ctx)
	}

	// 获取下一个文件表单
	part, err := reader.NextPart()
	if err != nil {
		return response.FailResult(1, "无法获取文件表单,"+err.Error(), ctx)
	}
	defer part.Close()

	// 创建目标文件
	dst, err := os.Create("/app/UpDateFile/" + part.FileName())
	if err != nil {
		return response.FailResult(1, "文件创建失败,"+err.Error(), ctx)
	}
	defer dst.Close()

	// 将文件内容复制到目标文件
	_, err = io.Copy(dst, part)
	if err != nil {
		return response.FailResult(1, "文件上传失败,"+err.Error(), ctx)
	}

	return response.SuccessResult("文件上传成功", ctx)
}

// 固件升级
func UploadUpgrade23(ctx echo.Context) error {
	// 通过FormFile函数获取客户端上传的文件
	fmt.Println("0")
	file, err := ctx.FormFile("upload_file")
	if err != nil {
		return err
	}
	//打开用户上传的文件
	fmt.Println("1")
	src, err := file.Open()
	if err != nil {
		return response.FailResult(1, "文件上传失败:"+err.Error(), ctx)
	}
	fmt.Println("2")
	defer src.Close()
	dst, err := os.Create("/app/UpDateFile/" + file.Filename)

	if err != nil {
		return response.FailResult(1, "文件上传失败:"+err.Error(), ctx)
	}
	defer dst.Close()

	// 使用缓冲区进行逐块复制
	buffer := make([]byte, 8192) // 8KB 缓冲区大小，可以根据需要调整
	for {
		n, err := src.Read(buffer)
		if err != nil {
			if err == io.EOF {
				break
			}
			return response.FailResult(1, "读取文件失败:"+err.Error(), ctx)
		}

		if _, err := dst.Write(buffer[:n]); err != nil {
			return response.FailResult(1, "写入文件失败:"+err.Error(), ctx)
		}
	}
	buffer = nil
	return response.SuccessResult("文件上传成功", ctx)
}
func UploadUpgrade2(ctx echo.Context) error {

	// 通过FormFile函数获取客户端上传的文件
	// file, err := ctx.FormFile("upload_file")
	// if err != nil {
	// 	return err
	// }
	//打开用户上传的文件
	file, err := os.Open("/app/GoApp_SL")
	if err != nil {
		return response.FailResult(1, "文件上传失败:"+err.Error(), ctx)
	}
	defer file.Close()

	dst, err := os.Create("/app/UpDateFile/1")

	if err != nil {
		return response.FailResult(1, "文件上传失败:"+err.Error(), ctx)
	}
	defer dst.Close()

	// 使用缓冲区进行逐块复制
	buffer := make([]byte, 8192) // 8KB 缓冲区大小，可以根据需要调整
	for {
		n, err := file.Read(buffer)
		if err != nil {
			if err == io.EOF {
				break
			}
			return response.FailResult(1, "读取文件失败:"+err.Error(), ctx)
		}

		if _, err := dst.Write(buffer[:n]); err != nil {
			return response.FailResult(1, "写入文件失败:"+err.Error(), ctx)
		}
	}

	// // 这里将用户上传的文件复制到服务端的目标文件
	// if _, err = io.Copy(dst, src); err != nil {
	// 	return response.FailResult(1, "上传失败:"+err.Error(), ctx)
	// }
	return response.SuccessResult("文件上传成功", ctx)
}

// 校时
func ChangeTime(ctx echo.Context) error {
	time := ctx.FormValue("time")
	err := pac.ChangeTimeS(time)
	if err != "" {
		return response.FailResult(1, err, ctx)
	}
	return response.SuccessResultWithEmptyData(ctx)

}
